﻿using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Huirui.Cavan.Domain.Seedwork;
using Spring.Context.Support;
using Huirui.Cavan.Domain.MainBoundedContext.PurchaseModule;
using Huirui.Cavan.Core.Extension;

namespace Huirui.Cavan.Application.MainBoundedContext.SystemModule
{
    public class SupplierAppService : BaseAppService<Supplier, string, SupplierSearch, ISupplierRepository>, ISupplierAppService
    {


        #region ISupplierAppService Members

        public override BoolGenericResult<Supplier> AddOrUpdate(Supplier entity)
        {
            Init();
            BoolGenericResult<Supplier> result = new BoolGenericResult<Supplier>();

            Employee employee = this.EmployeeAppService.GetBySearch(SearchFactory.CreateEmployeeSearch(SecurityAppService.UserAccount.Id)).FirstOrDefault();
            Purchaser purchaser = new Purchaser(employee);

            Supplier oldSupplier = null;
            if (entity.Id.IsNotEmpty())
            {
                oldSupplier = this.Repository.Get(entity.Id);
            }

            if (oldSupplier.IsNull())
            {
                IIDGenerateAppService idGenerateAppService = this.SpringContext.GetObject(SystemModuleConst.IDGENERATEAPPSERVICE, new object[] { employee.Corporation }) as IIDGenerateAppService;
                entity.Id = idGenerateAppService.GenerateID(SystemIdentifier.BaseCodeRuleType.Supplier);
                result = purchaser.ContractSupplier(entity.Id, entity.Nature, entity.Name, entity.Type, entity.Contact, entity.Telephone, entity.Mobile, entity.Fax, entity.Email, entity.Area,
                    entity.Address, entity.AddressEnglish, entity.DeliveryAddress1, entity.DeliveryAddress2, entity.PayType, entity.DiscountRate, entity.PayDay, entity.CreditLimit, entity.DefaultTaxRate,
                    entity.Remark);
                if (result.IsSuccess)
                    return base.Add(result.Object);
            }
            else
            {
                result = purchaser.UpdateSupplier(oldSupplier, entity.Nature, entity.Name, entity.Type, entity.Contact, entity.Telephone, entity.Mobile, entity.Fax, entity.Email, entity.Area,
                    entity.Address, entity.AddressEnglish, entity.DeliveryAddress1, entity.DeliveryAddress2, entity.PayType, entity.DiscountRate, entity.PayDay, entity.CreditLimit, entity.DefaultTaxRate,
                    entity.Remark);
                if (result.IsSuccess)
                    return base.Update(result.Object);
            }
            return result;
        }
        #endregion
    }
}
